//
//  QRCodeManager.swift
//  YuanJuBian
//
//  Created by PerhapYs on 2022/1/10.
//

import Foundation
// 生成二维码
final class QRCodeManager {
    
    class func generate(from string: String) -> UIImage? {
        
        let context = CIContext()
        
        //        let data = string.data(using: String.Encoding.ascii)
        let data = string.data(using: String.Encoding.utf8)
        
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setDefaults()
            
            filter.setValue(data, forKeyPath: "inputMessage")
            
            let transform = CGAffineTransform(scaleX: 7, y: 7)
            
            if let output = filter.outputImage?.transformed(by: transform), let cgImage = context.createCGImage(output, from: output.extent) {
                return UIImage(cgImage: cgImage)
            }
        }
        return nil
    }
    
    // 高清处理 -- 生成二维码
    static func createUIImageFromCIImage(image: CIImage, size: CGFloat) -> UIImage {
         let extent = image.extent.integral
         let scale = min(size / extent.width, size / extent.height)
             
         /// Create bitmap
         let width: size_t = size_t(extent.width * scale)
         let height: size_t = size_t(extent.height * scale)
         let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
         let bitmap: CGContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 1)!
        
         ///
         let context = CIContext.init()
         let bitmapImage = context.createCGImage(image, from: extent)
         bitmap.interpolationQuality = .none
         bitmap.scaleBy(x: scale, y: scale)
         bitmap.draw(bitmapImage!, in: extent)
             
         let scaledImage = bitmap.makeImage()
         return UIImage.init(cgImage: scaledImage!)
     }
}
